package com.hison.handler.security;

import com.alibaba.fastjson.JSON;
import com.hison.enums.AppHttpCodeEnum;
import com.hison.util.ResponseResult;
import com.hison.util.WebUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName: AccessDeniedHandlerImpl
 * @Descripiton: 自定义授权失败处理器
 * @Author: 小郑
 * @Date： 2024/1/13 14:00
 * @Version：1.8
 **/
@Configuration
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
        //打印异常信息
        e.printStackTrace();
        //ResponseResult、AppHttpCodeEnum是我们在huanf-framework工程写的类。重点在下面那行的枚举，就是我们返回给前端的信息
        ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);

        //使用spring提供的JSON工具类，把上一行的result转换成JSON，然后响应给前端。WebUtils是我们写的类
        WebUtils.renderString(response, JSON.toJSONString(result));
    }
}